package com.mephi.oshs.view.lang;

import com.mephi.oshs.Main;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Properties;

public class TextManager {
    private static final Logger logger = LoggerFactory.getLogger(TextManager.class);
    private static final Bundle BUNDLE = Main.getBundleContext().getBundle();
    private static final Charset CHARSET = Charset.forName("UTF-8");
    private static final String DEFAULT_LABEL = "Unknown label";

    private static final HashMap<Languages, TextManager> MULTITON = new HashMap<Languages, TextManager>();

    private final Properties properties = new Properties();

    private TextManager(final Languages language) {
        try {
            final InputStream stream = BUNDLE.getEntry(language.getPropertiesFile()).openStream();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, CHARSET));
            this.properties.load(reader);
        } catch (IOException e) {
            logger.error("TextManager(): Can't create Text Manager for language: " + language, e);
        }
    }

    public static synchronized TextManager getInstance(final Languages language) {
        if (!MULTITON.containsKey(language)) {
            MULTITON.put(language, new TextManager(language));
        }
        return MULTITON.get(language);
    }

    public String getText(final Labels label) {
        return this.properties.getProperty(label.name(), DEFAULT_LABEL);
    }
}
